/**
 * 滑动验证码方法
 * 
 * @author Ben
 * @version 2021.1.29
 */

function verify(node, callback) {
	const bgImgWidth = 280; //背景图片宽度
	const defectImageWidth = 50; //缺失块宽度

	var box = document.querySelector(node);
	// 初始化html元素
	box.innerHTML =
		'<div class="verifyImg-box">' +
		'	<h3 class="title">拖动图片完成验证</h3>' +
		'	<div class="img-box">' +
		'		<img class="bg-img">' +
		'		<div class="defectImage">' +
		'			<img src="" />' +
		'		</div>' +
		'	</div>' +
		'	<div class="slider-bar">' +
		'		<div class="bar-light"></div>' +
		'		<button type="button" class="slider-btn"></button>' +
		'	</div>' +
		'</div>';

	var sliderBtn = box.querySelector('.slider-btn');
	var bgImg = box.querySelector('.bg-img');
	var defectImage = box.querySelector('.defectImage');
	var lightBar = box.querySelector('.bar-light');

	// 刷新图片
	this.flush = function (data) {
		bgImg.src = data.backgroundImage;
		defectImage.querySelector('img').src = data.defectImage;
		defectImage.style.top = data.offsetHeight + 'px';
	}

	// 滑动位移相关
	var startPageX = 0;
	var startPageY = 0;
	var startTime = 0;
	var isMoving = false;
	var trailArray = [];

	sliderBtn.onmousedown = function (_event) {
		isMoving = true;
		startPageX = _event.pageX;
		startPageY = _event.pageY;
		startTime = new Date().getTime();
		trailArray = [];
		window.onmousemove = function (event) {
			var xTrail = event.pageX - startPageX;
			var yTrail = event.pageY - startPageY;
			moving(xTrail);
			saveTrail(xTrail, yTrail);
		}
	}

	sliderBtn.ontouchstart = function (_event) {
		isMoving = true;
		startPageX = event.targetTouches[0].pageX;
		startPageY = event.targetTouches[0].pageY;
		startTime = new Date().getTime();
		trailArray = [];
		window.ontouchmove = function (event) {
			var xTrail = event.targetTouches[0].pageX - startPageX;
			var yTrail = event.targetTouches[0].pageY - startPageY;
			moving(xTrail);
			saveTrail(xTrail, yTrail);
		}
	}

	window.ontouchend = window.onmouseup = function () {
		if (!isMoving) {
			return;
		}
		var leftLength = defectImage.offsetLeft;
		window.ontouchmove = window.onmousemove = null;
		callback(leftLength, trailArray);
		moving(0);
		isMoving = false;
	}

	function moving(leftLength) {
		if (leftLength < 0) {
			leftLength = 0;
		}
		else if (leftLength > bgImgWidth - defectImageWidth) {
			leftLength = bgImgWidth - defectImageWidth;
		}
		sliderBtn.style.left = leftLength + 'px';
		defectImage.style.left = leftLength + 'px';
		lightBar.style.width = leftLength + 10 + 'px';
	}

	function saveTrail(xTrail, yTrail) {
		var nowTime = new Date().getTime();
		var time = nowTime - startTime;
		// 大于10秒的，则直接抛弃
		if (time > 10000) {
			return;
		}
		var trail = [xTrail, yTrail, time];
		trailArray.push(trail);
	}

}
